var tz = tz || {},
    $$ = tz;

/**
 * 日志
 */
$$.log = function(obj) {
    if ( $$.cfg._debugger && console) {
        console.log(obj);
    }
};

/**
 * ajax 全局默认设置
 */
$.ajaxSetup({
    error: function(jqXHR, status, error) {
        switch (jqXHR.status) {
            case 401:
                $$.timeOut();
                break;
            case 403:
            	$$.alert("非法请求，请检查输入内容！");
                break;
            case 404:
                $$.alert("未找到资源(" + this.url + ")，请联系管理员");
                break;
            default:
                if (!jqXHR.responseText) {
                    //$$.alert("服务异常，请联系管理员");
                	if (console) {
                        console.log(jqXHR);
                    }
                    break;
                }
                try {
                    var data = eval("(" + jqXHR.responseText + ")");
                    switch (data.status) {
                        case 404:
                            //$$.alert("未找到资源(" + this.url + ")，请联系管理员");
                            if (console) {
                                console.log("未找到资源(" + this.url + ")，请联系管理员");
                            }
                            break;
                        default:
                            if (data.message) {
                                $$.alert(data.message + "(code=" + data.status + ")");
                            } else {
                                //$$.alert("服务异常，请联系管理员");
                                if (console) {
                                    console.log(data);
                                }
                            }
                    }
                } catch (e) {
                    //$$.alert("服务异常，请联系管理员");
                    if (console) {
                        console.log(e);
                    }
                }
                break;
        }
    }
});

$$.timeOut = function(){
    var waitSeconds = 5;
    var topL = function() {
        window.top.location.href = tz.url("/");
    };
    var id = $$.alert("<div style='margin-bottom:10px;'>您的身份认证已过期，请重新登录！</div><font color='red'>"
        + waitSeconds + "</font>秒后自动跳转到登录界面...", function(action) {
        topL();
    });
    var interval = setInterval(function() {
        waitSeconds--;
        if (waitSeconds == 0) {
            clearInterval(interval);
            topL();
        } else {
            $(".mini-messagebox-content-text font").html(waitSeconds);
        }
    }, 1000);

};

$$.winHeight = function() {
    return $(window).height();
}

$$.winWidth = function() {
    return $(window).width();
}

$$.trim = function(str) {
    return str.replace(/(^\s*)|(\s*$)/g, '');
};

$$.ltrim = function(str) {
    return str.replace(/(^\s*)/g, '');
};

$$.rtrim = function(str) {
    return str.replace(/(\s*$)/g, '');
};

$$.startWith = function(source, str) {
    var reg = new RegExp("^" + str);
    return reg.test(source);
};

$$.endWith = function(source, str) {
    var reg = new RegExp(str + "$");
    return reg.test(source);
};


function isFullscreenEnabled() {
    return document.fullscreenEnabled ||
        document.mozFullScreenEnabled ||
        document.webkitFullscreenEnabled ||
        document.msFullscreenEnabled || false;
}

function fullScreen(el) {
    var rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen,
        wscript;

    if (typeof rfs != "undefined" && rfs) {
        rfs.call(el);
        return;
    }

    if (typeof window.ActiveXObject != "undefined") {
        wscript = new ActiveXObject("WScript.Shell");
        if (wscript) {
            wscript.SendKeys("{F11}");
        }
    }
}

function exitFullScreen(el) {
    var el = document,
        cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen,
        wscript;

    if (typeof cfs != "undefined" && cfs) {
        cfs.call(el);
        return;
    }

    if (typeof window.ActiveXObject != "undefined") {
        wscript = new ActiveXObject("WScript.Shell");
        if (wscript != null) {
            wscript.SendKeys("{F11}");
        }
    }
}


/**
 * 
 */
$$.urlEncode = function(param, key, encode) {
    if (param == null)
        return '';
    var paramStr = '';
    var t = typeof(param);
    if (t == 'string' || t == 'number' || t == 'boolean') {
        paramStr += '&' +
            key +
            '=' +
            ((encode == null || encode) ? encodeURIComponent(param) :
                param);
    } else {
        if (!isNaN(param) && !isNaN(Date.parse(param))) {　　
            paramStr += '&' +
                key +
                '=' +
                ((encode == null || encode) ? encodeURIComponent(param) :
                    param);
        } else {
            for (var i in param) {
                var k = key == null ? i : key +
                    (param instanceof Array ? '[' + i + ']' : '.' + i);
                paramStr += $$.urlEncode(param[i], k, encode);
            }
        }
    }
    return paramStr;
};

$$.url = function(url, param) {
    if (!$$.startWith(url, $$.cfg.base) && !$$.startWith(url, "http") && !$$.startWith(url, "https")) {
        url = $$.cfg.base + url;
    }
    if(param){
        var paramStr = $$.urlEncode(param);

        if (url.indexOf("?") == -1) {
            url += "?" + paramStr.substr(1);
        } else {
            url += paramStr;
        }
    }
    return url;
};

$$.isBlank = function(e){
    if (e == null || String(e) == "" || typeof (e) == "undefined") {
        return true;
    } else {
        return false;
    }
};

$$.urlParse = function(url) {
    var matcht = /^(?:([A-Za-z]+):)?(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
    var result = matcht.exec(url);
    var names = ["url", "scheme", "slash", "host", "port", "path", "query", "hash"];
    var _URL = {};
    for (var i = 0, l = names.length; i < l; i++) {
        tz.log(names[i] + ":" + result[i]);
        _URL[names[i]] = result[i];
    }
    return _URL;
}

$$.route = function(url, param) {
    url = $$.url(url, param);
    var locationURL = $$.urlParse(location.href);
    var targetURL = $$.urlParse(url);
    if (targetURL) {
        url = (locationURL.scheme + ":" + locationURL.slash);
        url += locationURL.host;
        if (locationURL.port) {
            url += (":" + locationURL.port);
        }

        if (targetURL.path) {
            url += ("/" + targetURL.path);
        }

        if (targetURL.query) {
            url += ("?" + targetURL.query);
        }

        if (targetURL.hash) {
            url += ("#" + targetURL.hash);
        }
    }
    return url;
}

/**
 * 数据脱敏 add zfx
 * @param data
 * @returns {string|*}
 */
$$.desensitization = function(data) {
    var t = typeof(data);
    if (t == 'string' || t == 'number') {
        // 正则判断返回相应数据
        if (/(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(data) || /^(13[0-9]|16[0-9]|19[0-9]|147|15[0-9]|17[6-8]|18[0-9])\d{8}|17[0-9]\d{8}$/.test(data) || /(^(?:(?![IOZSV])[\dA-Z]){2}\d{6}(?:(?![IOZSV])[\dA-Z]){10}$)|(^\d{15}$)/.test(data)) {
            //身份证号 || 手机号 || 营业执照    前三后四
            data = data.substr(0, 3) + "****" + data.substr(-4);
        } else if (/^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$/.test(data)) {
            //邮箱号码  前二 后以 @ 分割
            data = data.substr(0, 2) + "****" + data.substr(data.indexOf('@'));
        } else if (/^\d{16}|\d{19}$/.test(data)) {
            //银行卡号  后四位
            data = "****" + data.substr(-4);
        } else if (data.indexOf('公司') > -1) {
            //企业名称  前二后四
            data = data.substr(0, 2) + "****" + data.substr(-4);
        }
        return data;
    } else {
        return data;
    }
}

$$.getQueryValue = function(url ,paramName){
    var result = [];
    var query = url.split("?")[1];
    if(query){
        var queryArr = query.split("&");
        for(var i =0;i< queryArr.length ; i++){
            var item = queryArr[i];
            var key = item.split("=")[0];
            if(key == paramName){
                var value = item.split("=")[1];
                return value;
            }
        }
    }
}

var console = console || {
	log : function(){
	    return false;
    }
};